<template>
  <div>
    <a-card :loading="loading">
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: baseline;
        "
      >
        <div style="font-size: 18px; font-weight: bolder"> 规则抬头 </div>
        <div>
          <a-button status="success" @click="save">保存</a-button>
        </div>
      </div>
      <a-divider margin="5"></a-divider>
      <a-form
        ref="formRef"
        :label-col-props="{ span: 6 }"
        :model="formData"
        :wrapper-col-props="{ span: 18 }"
      >
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="规则名称">
              <a-input v-model="formData.name" placeholder="请输入规则名称" />
            </a-form-item>
          </a-col>
          <a-col v-if="routeType === 'COSTTYPE'" :span="8">
            <a-form-item label="账套编码">
              <a-input
                v-model="formData.accountSetId"
                placeholder="请输入账套编码"
              />
            </a-form-item>
          </a-col>
          <a-col v-if="routeType === 'COSTTYPE'" :span="8">
            <a-form-item label="账套名称">
              <a-input
                v-model="formData.accountSetName"
                placeholder="请输入账套名称"
              />
            </a-form-item>
          </a-col>
          <a-col v-if="routeType === 'COSTTYPE'" :span="8">
            <a-form-item label="费用类型">
              <select-multiple-filter
                :data="formData.chargeTypeList"
                :default-value="
                  formData.chargeTypeList.map((x) => x.chargeType)
                "
                type="chargeType"
                @change="chargeTypeChange"
              ></select-multiple-filter>
            </a-form-item>
          </a-col>
          <a-col v-if="routeType === 'COSTTYPE'" :span="8">
            <a-form-item label="发票类型">
              <select-multiple-filter
                :data="formData.invoiceTypeList"
                :default-value="
                  formData.invoiceTypeList.map((x) => x.invoiceType)
                "
                type="invoiceType"
                @change="invoiceTypeChange"
              ></select-multiple-filter>
            </a-form-item>
          </a-col>
          <a-col v-if="routeType === 'COSTTYPE'" :span="8">
            <a-form-item label="部门">
              <select-multiple-filter
                :data="formData.departmentList"
                :default-value="
                  formData.departmentList.map((x) => x.departmentId)
                "
                type="department"
                @change="departmentChange"
              ></select-multiple-filter>
            </a-form-item>
          </a-col>
          <a-col v-if="routeType === 'PAYTYPE'" :span="8">
            <a-form-item label="付款方式">
              <select-multiple-filter
                :data="formData.payWayList"
                :default-value="formData.payWayList.map((x) => x.payWay)"
                type="payWay"
                @change="payWayChange"
              ></select-multiple-filter>
            </a-form-item>
          </a-col>
          <a-col v-if="routeType === 'PAYTYPE'" :span="8">
            <a-form-item field="bodyType" label="主体类型">
              <a-select v-model="formData.bodyType" placeholder="请选择">
                <a-option
                  v-for="(item, key) in bodyTypeOptions"
                  :key="key"
                  :value="item.label"
                  >{{ item.value }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col v-if="routeType === 'PAYTYPE'" :span="8">
            <a-form-item label="银行账户">
              <a-input
                v-model="formData.bankCode"
                placeholder="请输入银行账户"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card>
      <a-divider orientation="right">
        <a-button type="primary" @click="addDetail">新增</a-button>
      </a-divider>
      <a-table
        :bordered="false"
        :data="formData.ruleItemList"
        :pagination="false"
        row-key="id"
      >
        <template #columns>
          <a-table-column :width="60" title="序号">
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column data-index="summary" title="摘要">
            <template #cell="{ record }">
              <a-button @click="summaryMethod(record)"
                >{{ record.summary ? getSummary(record.summary) : '请选择' }}
              </a-button>
            </template>
          </a-table-column>
          <a-table-column data-index="subjectCode" title="科目">
            <template #cell="{ record }">
              <a-button @click="subjectMethod(record)"
                >{{ record.subjectName ? record.subjectName : '请选择' }}
              </a-button>
            </template>
          </a-table-column>
          <a-table-column data-index="debitColumn" title="借方金额字段">
            <template #cell="{ record }">
              <a-select
                v-model="record.debitColumn"
                placeholder="请选择"
                @change="debitChange"
              >
                <a-option
                  v-for="(item, key) in options"
                  :key="key"
                  :value="item.id"
                  >{{ item.name }}
                </a-option>
              </a-select>
            </template>
          </a-table-column>
          <a-table-column data-index="creditColumn" title="贷方金额字段">
            <template #cell="{ record }">
              <a-select
                v-model="record.creditColumn"
                placeholder="请选择"
                @change="creditChange"
              >
                <a-option
                  v-for="(item, key) in options"
                  :key="key"
                  :value="item.id"
                  >{{ item.name }}
                </a-option>
              </a-select>
            </template>
          </a-table-column>
          <a-table-column
            :title="$t('columns.operations')"
            data-index="operations"
            fixed="left"
            :width="60"
          >
            <template #cell="{ record }">
              <a-popconfirm
                :content="$t('operations.popConfirm.delete')"
                type="error"
                @ok="handleClickToDel(record.id)"
              >
                <a-button type="text" size="small" status="danger">
                  {{ $t('columns.operations.delete') }}
                </a-button>
              </a-popconfirm>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
    <invoice-summary
      ref="summaryModalRef"
      @select="summarySelect"
    ></invoice-summary>
    <invoice-subject
      ref="subjectModalRef"
      @select="subjectSelect"
    ></invoice-subject>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import {
    columnList,
    detailRule,
    ResultVO,
    RuleItemVO,
    updateRule,
    VoucherRuleDTO,
  } from '@/api/invoice';
  import SelectMultipleFilter from '@/components/select-multiple-filter/index.vue';
  import { Message } from '@arco-design/web-vue';
  import InvoiceSummary from '@/views/invoice/components/invoice-summary.vue';
  import useLoading from '@/hooks/loading';
  import InvoiceSubject from '@/views/invoice/components/invoice-subject.vue';
  import { useRoute } from 'vue-router';
  import { convertTemplateToStr, convertTemplateToTags } from '@/utils/tools';
  import { TagData } from '@arco-design/web-vue/es/input-tag/interface';

  const routeType = useRoute().meta.type;
  const routeTypeName = useRoute().meta.typeName;
  const formData = ref<VoucherRuleDTO>({
    accountSetId: '',
    accountSetName: '',
    bankCode: '',
    bodyType: '',
    chargeTypeList: [],
    departmentList: [],
    enableFlag: '',
    id: '',
    invoiceTypeList: [],
    name: '',
    payWayList: [],
    ruleItemList: [],
    typeId: '',
    typeName: '',
  });
  const subjectModalRef = ref();
  const summaryModalRef = ref();
  const options = ref<ResultVO[]>([]);
  const summaryOptions = ref<ResultVO[]>([]);
  const { loading, setLoading } = useLoading();
  const bodyTypeOptions = [
    { value: '客户', label: '客户' },
    { value: '供应商', label: '供应商' },
    {
      value: '员工',
      label: '员工',
    },
  ];

  const getInvoiceDetail = async (id: string) => {
    try {
      setLoading(true);
      const { data } = await detailRule(id);
      formData.value = data;
      console.log(formData.value.chargeTypeList.map((x) => x.chargeType));
    } catch (e) {
      // you can report use errorHandler or other
      console.log(e);
    } finally {
      formData.value.id = id;
      setLoading(false);
    }
  };
  const chargeTypeChange = (data: { keys: string[]; options: ResultVO[] }) => {
    formData.value.chargeTypeList = [];
    data.options.forEach((item) => {
      if (data.keys.includes(item.id)) {
        formData.value.chargeTypeList.push({
          chargeType: item.id,
          chargeTypeName: item.name,
        });
      }
    });
  };
  const invoiceTypeChange = (data: { keys: string[]; options: ResultVO[] }) => {
    formData.value.invoiceTypeList = [];
    data.options.forEach((item) => {
      if (data.keys.includes(item.id)) {
        formData.value.invoiceTypeList.push({
          invoiceType: item.id,
          invoiceTypeName: item.name,
        });
      }
    });
  };
  const departmentChange = (data: { keys: string[]; options: ResultVO[] }) => {
    formData.value.departmentList = [];
    data.options.forEach((item) => {
      if (data.keys.includes(item.id)) {
        formData.value.departmentList.push({
          departmentId: item.id,
          departmentName: item.name,
        });
      }
    });
  };
  const payWayChange = (data: { keys: string[]; options: ResultVO[] }) => {
    formData.value.payWayList = [];
    data.options.forEach((item) => {
      if (data.keys.includes(item.id)) {
        formData.value.payWayList.push({
          payWay: item.id,
          payWayName: item.name,
        });
      }
    });
  };
  const addDetail = () => {
    const index = formData.value.ruleItemList.length;
    formData.value.ruleItemList.push({
      id: index.toString(),
      creditColumn: '',
      creditColumnName: '',
      debitColumn: '',
      debitColumnName: '',
      headId: formData.value.id,
      subjectCode: '',
      subjectName: '',
      summary: '',
      voucherRule: '',
    });
  };
  const subjectSelect = (data: { selectRow: any; row: RuleItemVO }) => {
    formData.value.ruleItemList.forEach((item: any) => {
      if (item.id === data.row.id) {
        item.subjectCode = data.selectRow.code;
        item.subjectName = data.selectRow.standardText;
      }
    });
  };
  const summarySelect = (data: { summary: string; row: RuleItemVO }) => {
    formData.value.ruleItemList.forEach((item: RuleItemVO) => {
      if (item.id === data.row.id) {
        item.summary = data.summary;
      }
    });
  };
  const subjectMethod = (row: RuleItemVO) => {
    if (subjectModalRef.value) {
      subjectModalRef.value.handleChangeVisible(row);
    }
  };
  const summaryMethod = (row: RuleItemVO) => {
    if (summaryModalRef.value) {
      summaryModalRef.value.handleChangeVisible(row);
    }
  };
  const save = async () => {
    try {
      formData.value.typeId = routeType as string;
      formData.value.typeName = routeTypeName as string;
      await updateRule(formData.value);
      Message.success('保存成功！');
    } catch (e) {
      Message.warning('保存失败！');
    }
  };
  const getSearch = async () => {
    try {
      const { data } = await columnList();
      if (data) {
        summaryOptions.value = data;
        data.forEach((item) => {
          if (item.name.indexOf('金额') !== -1) {
            options.value.push(item);
          }
        });
      }
    } catch (e) {
      // 错误处理
    }
  };
  const debitChange = (value: string) => {
    const selected = options.value.find((item) => item.id === value);
    if (selected) {
      formData.value.ruleItemList.forEach((item) => {
        if (item.debitColumn === value) {
          item.debitColumnName = selected.name;
        }
      });
    }
  };
  const creditChange = (value: string) => {
    const selected = options.value.find((item) => item.id === value);
    if (selected) {
      formData.value.ruleItemList.forEach((item) => {
        if (item.creditColumn === value) {
          item.creditColumnName = selected.name;
        }
      });
    }
  };
  const handleClickToDel = (id: string) => {
    formData.value.ruleItemList = formData.value.ruleItemList.filter(
      (x) => x.id !== id
    );
  };
  const getSummary = (summary: string): string => {
    let modelValue = '';
    if (summary) {
      modelValue = convertTemplateToStr(summary, summaryOptions.value);
    }
    return modelValue;
  };
  getSearch();
  defineExpose({ getInvoiceDetail });
</script>

<style lang="less" scoped></style>
